package com.fw.ui.util.validator;

public class StringLengthValidator extends com.vaadin.data.validator.StringLengthValidator {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private Integer minLength = null;
    private Integer maxLength = null;
    private boolean allowNull = true;

    public StringLengthValidator(String errorMessage) {
	super(errorMessage);
    }

    public StringLengthValidator(String errorMessage, Integer minLength, Integer maxLength, boolean allowNull) {
	super(errorMessage, minLength, maxLength, allowNull);
	this.allowNull = allowNull;
	this.minLength = minLength;
	this.maxLength = maxLength;
    }

    @Override
    protected boolean isValidValue(String value) {
	if (value == null || value.trim().length() == 0) {
	    return allowNull;
	}
	final int len = value.length();
	if ((minLength != null && minLength > -1 && len < minLength) || (maxLength != null && maxLength > -1 && len > maxLength)) {
	    return false;
	}
	return true;
    }

    /**
     * Returns <code>true</code> if null strings are allowed.
     * 
     * @return <code>true</code> if allows null string, otherwise <code>false</code>.
     */
    public boolean isNullAllow() {
	return allowNull;
    }

    /**
     * Gets the maximum permissible length of the string.
     * 
     * @return the maximum length of the string or null if there is no limit
     */
    public Integer getMaxLength() {
	return maxLength;
    }

    /**
     * Gets the minimum permissible length of the string.
     * 
     * @return the minimum length of the string or null if there is no limit
     */
    public Integer getMinLength() {
	return minLength;
    }

    /**
     * Sets whether null-strings are to be allowed. This can be better handled
     * by setting a field as required or not.
     */
    public void setNullAllowed(boolean allowNull) {
	this.allowNull = allowNull;
    }

    /**
     * Sets the maximum permissible length of the string.
     * 
     * @param maxLength
     *            the maximum length to accept or null for no limit
     */
    public void setMaxLength(Integer maxLength) {
	this.maxLength = maxLength;
    }

    /**
     * Sets the minimum permissible length.
     * 
     * @param minLength
     *            the minimum length to accept or null for no limit
     */
    public void setMinLength(Integer minLength) {
	this.minLength = minLength;
    }

}
